<template>
  <div>
    <van-pull-refresh v-model="isLoading" @refresh="onRefresh">
      <!-- <p>刷新次数: {{ count }}</p> -->
      <!-- 头部图片 -->
      <div style="width:100%;background-image:url(assets/tab1_header.png);margin-top: 0px;height:150px;">
        <van-row>
          <van-col style="color:white;margin-top: 40px;margin-left:10%;"><van-icon size="25" name="assets/message.png"
              @click="jumpOther('push_message', './my-pushMessage.html')" :badge="messageNum" /></van-col>
          <van-col style="color:white;margin-top: 40px;margin-left:20%;">{{ user.nickName }}</van-col>
          <van-button :block="true" class="buttonLeft" @click="selectAll" type="primary" :text="selectFont" />
        </van-row>

        <van-row>
          <van-col style="color:white;margin-top: 30px;margin-left:10%;">设备总数</van-col>
          <van-col style="color:white;margin-top: 30px;margin-left:50%;">实时故障</van-col>
        </van-row>
        <van-row>
          <van-col style="color:white;margin-top: 5px;margin-left:15%;">{{ equipmentInfo.equipmentNum }}</van-col>
          <van-col style="color:white;margin-top: 5px;margin-left:64%;">{{ equipmentInfo.requestNum }}</van-col>
        </van-row>
      </div>
      <!-- 图片结束 -->
    </van-pull-refresh>

    <!-- 菜单 -->
    <div class="textScroll">
      <Row class="menu-col">
        <div v-for="(parent, index) in list">
          <div v-if="parent.children && parent.hidden == false">
            <NoticeBar color="#224C64" background="#F2F4F7" style="height:8px;" :left-icon="parent.meta.icon">
            </NoticeBar>
            <!-- <div v-show="indexnex(index)"> -->
            <div v-if="parent.perems == 'task_execute'">
              <Col span="6" v-for="child in parent.children">
              <Icon :name="child.component" size="3rem" @click="openwithDialog(child.path, child.perems)" />
              <span style="font-size:15px;">{{ child.meta.title }}</span>
              </Col>
            </div>
            <div v-else>
              <div v-if="parent.hidden == false">
                <van-row style="margin-top:10px;" @click="tms(index)">
                  <!-- <van-col>
                    <van-image width="20" height="20" src="assets/block.png" />
                  </van-col> -->

                  <div v-if="parent.meta.icon == 'button'">
                    <van-col>
                      <van-image width="20" height="20" src="assets/block.png" />
                    </van-col>
                    <van-col style="color:#224C64;margin-left: 5px;">{{ parent.meta.title }}</van-col>
                  </div>
                  <div v-if="parent.meta.icon != 'button'">
                    <div v-if="parent.meta.num == '0'">
                      <van-col>
                        <van-image width="20" height="20" src="assets/block.png" />
                      </van-col>
                      <van-col style="color:#224C64;margin-left: 5px;">{{ parent.meta.title }}</van-col>
                    </div>
                    <div v-else>
                      <van-col>
                        <van-image width="20" height="20" src="assets/block.png" />
                      </van-col>
                      <van-badge :content="parent.meta.num" max="999">
                        <div class="child" />
                        <van-col style="color:#224C64;margin-left: 5px;">{{ parent.meta.title }}</van-col>
                      </van-badge>
                    </div>

                  </div>
                </van-row>
              </div>
              <Col span="5" v-for="child in parent.children" v-show="indexnex[index]" style="margin-top: 7px;">
              <div v-if="child.hidden == false">
                <div v-if="child.meta.icon == '404'">
                  <div class="child" />
                  <Icon :name="child.component" size="2.5rem" @click="open(child.path, child.perems, child.meta.title)" />
                  <br />
                  <van-col style="font-size:13px;color:black;"
                    @click="open(child.path, child.perems, child.meta.title)">{{
                      child.meta.title }}</van-col>
                </div>
                <div v-if="child.meta.icon == 'bug'">
                  <van-badge :content="child.meta.num">
                    <div class="child" />
                    <Icon :name="child.component" size="2.5rem"
                      @click="open(child.path, child.perems, child.meta.title)" />
                    <br />
                    <van-col style="font-size:13px;color:black;"
                      @click="open(child.path, child.perems, child.meta.title)">{{
                        child.meta.title }}</van-col>
                  </van-badge>
                </div>
                <div v-if="child.meta.icon == 'build'">
                  <div v-if="child.meta.num != '0'">
                    <van-badge dot>
                      <div class="child" />
                      <Icon :name="child.component" size="2.5rem"
                        @click="open(child.path, child.perems, child.meta.title)" />
                      <br />
                      <van-col style="font-size:13px;color:black;"
                        @click="open(child.path, child.perems, child.meta.title)">{{
                          child.meta.title }}</van-col>
                    </van-badge>
                  </div>

                  <div v-else>
                    <Icon :name="child.component" size="2.5rem"
                      @click="open(child.path, child.perems, child.meta.title)" />
                    <br />
                    <van-col style="font-size:13px;color:black;"
                      @click="open(child.path, child.perems, child.meta.title)">{{
                        child.meta.title }}</van-col>
                  </div>

                </div>

                <!-- <div v-if="child.path == 'my-pushMessageM'">
                  <van-badge :content="notReadNum">
                    <div class="child" />
                    <Icon :name="child.component" size="2.5rem"
                      @click="open(child.path, child.perems, child.meta.title)" />
                    <br />
                    <van-col style="font-size:13px;color:black;"
                      @click="open(child.path, child.perems, child.meta.title)">{{
                        child.meta.title }}</van-col>
                  </van-badge>
                </div> -->
              </div>
              </Col>
            </div>
            <!-- </div> -->
          </div>
        </div>
        <!-- <Col span="6" v-for="item in list" :key="item.id">
          <Icon :name="item.icon" size="2rem" @click="open(item.path, item.alias, item.menuName)" />
          <span>{{ item.name }}</span>
        </Col> -->
      </Row>
    </div>
    <!-- 菜单结束 -->

    <ActionSheet v-model="actionSheetShow" :actions="actions" description="请选择任务类型" close-on-click-action
      @select="onSelect" />
    <!-- <a @click="getUser">dasdasdas</a> -->
  </div>
</template>

<script>
import apicloud from '@/libs/apicloud'
import {
  Badge,
  Search,
  Toast,
  Icon,
  Row,
  Col,
  NoticeBar,
  ActionSheet,
  Image as VanImage,
  Dialog,
  PullRefresh,
  Button,
} from 'vant'
Vue.use(Col)
Vue.use(Row)
Vue.use(VanImage)
Vue.use(Dialog)
Vue.use(PullRefresh)
Vue.use(Icon)
Vue.use(Button)
Vue.use(Badge)

import { _httpClient, bindAliasAndTags } from '@/libs/api'
import { storage, memory, globelTimer } from '@/libs/utils'
import { getToken } from '@/libs/auth'
import { _httpClient as _httpClientSIE } from "@/libs/apisie";
import { relativeTimeRounding, relativeTimeThreshold } from 'moment'
import { number } from 'echarts'
// import YSF from '@neysf/qiyu-web-sdk';

export default {
  name: 'tab1',
  components: { Button, Search, Icon, Col, Row, Toast, NoticeBar, ActionSheet, Badge },
  data() {
    return {
      tes: false,
      indexnex: [],
      notReadNum: "0",
      messageNum: "0",
      count: 0,
      isLoading: false,
      selectFont: '上班打卡',
      user: [], //用户信息
      list1: [],
      list2: [{ name: "Tightenup", num: 0 }, { name: "YCCPCL", num: 0 }, { name: "TJ", num: 0 }, { name: "FG", num: 0 }, { name: "My", num: 0 }],
      actionSheetShow: false,
      actions: [
        { id: '1', name: '运行任务' },
        { id: '0', name: '停机任务' },
      ],
      equipmentInfo: [], //设备信息
      list: [],
      queryParams: {
        mnType: '',
        eqStatus: '',
        taskType: '',
      },
      menuRoute: '',
      loading: false,
      finished: false,
    }
  },
  created() {
    let that = this;
    if (storage.get('user') != '' && storage.get('user') != undefined) {
      // that.queryEquipmentInfo()
      // that.queryUserInfo()
    }
    //that.initbaoxiaozhi();
    that.user = JSON.parse(storage.get('user'))
    //绑定极光推送
    bindAliasAndTags(that.user.userName)

    api.addEventListener({ name: 'appintent' }, function (ret, err) {
      // alert('通知被点击，收到数据：\n' + JSON.stringify(ret))
      //监听通知被点击后收到的数据
      if (ret && ret.appParam.ajpush) {
        var ajpush = ret.appParam.ajpush
        //  alert(ajpush);
        // var id = ajpush.id
        // //  alert(id);
        // var title = ajpush.title
        // var content = ajpush.content
        // var extra = ajpush.extra

        Dialog.alert({
          message: ajpush.content,
        }).then(() => {
          // on close
        })
      }
    })

    that.list = JSON.parse(storage.get('menu'));
    //查询明细数量
    //修改父节点明细，更改子节点明细数据

    //alert(JSON.stringify(that.list));
    //that.querynum();
    that.equipmentInfo = JSON.parse(storage.get('equipmentInfo'));
  },

  mounted() {
    //监听登录事件
    let that = this
    api.addEventListener({ name: 'loginSuccess' }, function (ret) {
      that.initPage()

      // that.initMenu()
      // that.queryUserInfo()
    })

    let tkn = getToken()
    if (!tkn) {
      api.openWin({
        name: 'login',
        url: './login-login.html',
        rect: {
          x: 0,
          y: 150,
          w: api.winWidth,
          h: api.winHeight,
        },
      })
    } else {
      that.initPage()
      // that.queryUserInfo()
    }

    //that.querynum();
  },
  methods: {
    initbaoxiaozhi(){
      // YSF.init('98193d444c97cac955924a5ac9fff29c').then(ysf => {
      //           ysf('open');
      //       }).catch(error => {
      //           console.log('sdk加载失败---', error);
      //       });
    },
    async queryNotReadList() {

      let _this = this;

      try {

        let res = await _httpClientSIE.get(
          _httpClientSIE.getApiPrefix() +
          "/MessageReceived/GetNotReadList?UserID=" + _this.user.userName + "&PageSize=1&PageIndex=1",
        );

        this.notReadNum = res.Total;
        var jsonObj1 = { "name": "My", "num": this.notReadNum };
        _this.list2.push(jsonObj1);
        _this.$forceUpdate();
        // alert(JSON.stringify(_this.list1));
        // alert(JSON.stringify(_this.list2));
      } catch (e) {
        this.notReadNum = 0
      }
    },
    checkval(val) {
      var flag = 0;
      //判断数组中是否有，如果没有则打开
      this.indexnex.forEach(function (item, index, arr) {
        if (item.key == val) {
          flag = 1;
        }
      })

      if (flag == 1) {
        var arr = new Array();
        arr[0] = val;
        arr[1] = 1;
        this.indexnex.push(arr);
        return 1;
      }

      this.indexnex.forEach(function (item, index, arr) {
        if (item.key == val) {
          if (item.value == true) {
            return 0;
          }
          else {
            return 1;
          }
        }
        else {
          return 0;
        }
      })
      //如果有则反转
    },
    tms(val) {
      // alert(val);
      // alert(this.indexnex);
      if (this.indexnex[val] == false) {
        this.indexnex[val] = true;
        //return true;
      } else {
        this.indexnex[val] = false;
        //return false;
      }
      this.$forceUpdate();
      //alert(val);
    },
    async getnewnum(name) {
      let _this = this
      try {
        let res = await _httpClient.post(
          _httpClient.getApiPrefix() +
          '/app/message/messageInfo/list',
          {
            body: { isRead: '0', notingUser: name },
          }
        )
        if (res.code === 200) {
          //alert(1234);
          //Toast.success(res.msg)
          //alert(JSON.stringify(res));
          _this.messageNum = res.total
        } else {
          //Toast.fail(res.msg)
        }
      } catch (e) {
        //Toast.fail(JSON.stringify(e))
      }
    },
    initPage() {
      this.initMenu().then((val) => {
        this.initMenu().then((val) => {
          this.queryUserInfo()
        })

        this.queryUserInfo()
      })
    },
    checkUserClockIn() {
      let that = this
      that.$ac.confirm(
        {
          title: '打卡',
          msg: '请选择当前是否上班？',
          buttons: ['上班', '下班'],
          type: 'error',
        },
        function (ret, err) {
          if (ret.buttonIndex == 1) {
            that.selectFont == '下班打卡'
            that.clockIn('1')
          } else if (ret.buttonIndex == 2) {
            that.selectFont == '上班打卡'
            that.clockIn('0')
          } else {
            that.checkUserClockIn()
          }
        }
      )
    },
    getUser() {
      this.user = JSON.parse(storage.get('user'))
    },

    //界面跳转
    jumpOther(route, urlValue) {
      api.openWin({
        name: route,
        url: urlValue,
        rect: {
          x: 0,
          y: 150,
          w: api.winWidth,
          h: api.winHeight,
        },
      })
    },

    async clockIn(clockinStatus) {
      let _this = this
      try {
        let res = await _httpClient.post(_httpClient.getApiPrefix() + '/app/user/userInfo/updateStatus', {
          body: { userKey: _this.user.userId, userAccound: _this.user.userName, clockin: clockinStatus },
        })
        if (clockinStatus == '0') {
          _this.selectFont = '上班打卡'
        } else {
          _this.selectFont = '下班打卡'
        }
      } catch (e) {
        //Toast.fail(e)
      }
    },

    selectAll() {
      let _this = this
      if (_this.selectFont == '下班打卡') {
        Dialog.confirm({
          title: '提示',
          message: '是否确认打卡下班?',
        })
          .then(() => {
            try {
              let res = _httpClient.post(_httpClient.getApiPrefix() + '/app/user/userInfo/updateStatus', {
                body: { userKey: _this.user.userId, userAccound: _this.user.userName, clockin: '0' },
              })
              Toast.clear()
              Toast.success('打卡成功')
              //取消極光推送
              _this.deleteAlias()
              _this.selectFont = '上班打卡'
            } catch (e) {
              //Toast.fail(e)
            }
          })
          .catch(() => { })
      } else {
        Dialog.confirm({
          title: '提示',
          message: '是否确认打卡上班?',
        })
          .then(() => {
            try {
              let res = _httpClient.post(_httpClient.getApiPrefix() + '/app/user/userInfo/updateStatus', {
                body: { userKey: _this.user.userId, userAccound: _this.user.userName, clockin: '1' },
              })
              Toast.clear()
              Toast.success('打卡成功')
              //激活激光推送
              //绑定极光推送
              bindAliasAndTags(_this.user.userName)
              _this.selectFont = '下班打卡'
            } catch (e) {
              //Toast.fail(e)
            }
          })
          .catch(() => { })
      }
      // this.selectFont = '下班打卡'
      // this.queryUserInfo()
    },

    //刷新界面相关设备数据信息
    onRefresh() {
      // this.queryEquipmentInfo()
      // this.queryUserInfo()
      // this.initMenu();

      setTimeout(() => {
        Toast('刷新成功')
        this.isLoading = false
        this.queryEquipmentInfo()
        this.queryUserInfo()
        this.initMenu();
        //绑定极光推送
        bindAliasAndTags(this.user.userName)

        api.addEventListener({ name: 'appintent' }, function (ret, err) {
          // alert('通知被点击，收到数据：\n' + JSON.stringify(ret))
          //监听通知被点击后收到的数据
          if (ret && ret.appParam.ajpush) {
            var ajpush = ret.appParam.ajpush
            Dialog.alert({
              message: ajpush.content,
            }).then(() => {
              // on close
            })
          }
        })
      }, 1000)
    },
    //查询设备数量、故障数量、和消息数量
    async queryEquipmentInfo() {
      this.getUser()
      let _this = this
      _this.getnewnum(_this.user.userName);
      try {
        let res = await _httpClient.post(_httpClient.getApiPrefix() + '/app/equipment/info', {
          body: { userName: _this.user.userName },
        })
        // alert(res)
        if (res.code === 200) {
          _this.equipmentInfo = res.rows[0]
          storage.set('equipmentInfo', _this.equipmentInfo)
        }
        Toast.clear()
      } catch (e) {
        //Toast.fail(e)
      }
    },
    async querynum() {
      let _this = this;
      _this.list2 = [{ name: "Tightenup", num: 0 }, { name: "YCCPCL", num: 0 }, { name: "TJ", num: 0 }, { name: "FG", num: 0 }, { name: "My", num: 0 }];
      _this.list1 = [];
      try {
        let res = await _httpClientSIE.get(
          _httpClientSIE.getApiPrefix() +
          '/FunctionProcessCount/GetList?EmployeeID=' + _this.user.userName,
        );
        //解析返回数据
        res.Data.forEach(element => {
          var lists = element.AppMenuID.split(";");
          var jsonObj1 = { "name": lists[1], "num": element.ProcessCount };
          _this.list1.push(jsonObj1);
          // _this.list2.forEach(element1 => {
          //   if (element1.name == lists[0]) {
          //     if (element.ProcessCount.indexOf("+") != -1) {
          //       var lst = element.ProcessCount.split("+");
          //       element1.num = (Number(element1.num) + Number(lst[0]) + Number(lst[1])).toString();
          //     } else {
          //       alert("element.ProcessCount="+element.ProcessCount);
          //       alert("前element1.num="+element1.num);
          //       element1.num = (Number(element1.num) + Number(element.ProcessCount)).toString();
          //       alert("后element1.num="+element1.num);
          //     }
          //   }
          // });
        });

        //_this.list2 = [{ name: "Tightenup", num: 0 }, { name: "YCCPCL", num: 0 }, { name: "TJ", num: 0 }, { name: "FG", num: 0 }, { name: "My", num: 0 }];

        //alert(JSON.stringify(_this.list1));
        //绑定返回数据
        _this.list.forEach(element1 => {
          _this.list2.forEach(element2 => {
            //父节点相同
            // if (element1.name == element2.name) {
            //   element1.meta.num = element2.num;
            // }
            element1.meta.num = "0";
            try {
              element1.children.forEach(element3 => {
                _this.list1.forEach(element4 => {
                  //子节点相同
                  if (element3.path == element4.name) {
                    element3.meta.num = element4.num;
                    if (element4.num.indexOf("+") != -1) {
                      var lst = element4.num.split("+");
                      element1.meta.num = (Number(element1.meta.num) + Number(lst[0]) + Number(lst[1])).toString();
                    } else {
                      //alert("element4.num=" + element4.num);
                      //alert("前element1.meta.num=" + element1.meta.num);
                      element1.meta.num = (Number(element1.meta.num) + Number(element4.num)).toString();
                      //alert("后element1.meta.num=" + element1.meta.num);
                    }
                  }
                });
              });
            } catch (err) {
              //alert(JSOM.stringiflist1y(err));
            }

          });
        });

        //alert(JSON.stringify(_this.list));
        //修正父节点数量
        _this.$forceUpdate();

      } catch (e) {
        Toast.fail("网络请求中...")
      }
    },
    //查询当前人员的上班状态
    async queryUserInfo() {
      let _this = this
      // alert(_this.user.userName )
      try {
        let res = await _httpClient.post(_httpClient.getApiPrefix() + '/app/user/userInfo/status1', {
          body: { userAccound: _this.user.userName },
        })
        // alert(res.rows[0].status)
        if (res.code === 200) {
          if (res.rows[0].clockin == '1') {
            _this.selectFont = '下班打卡'
          } else {
            _this.selectFont = '上班打卡'
          }
          storage.set('selectFont', _this.selectFont)
          if (_this.selectFont == '上班打卡') {
            _this.checkUserClockIn()
          }
        }
        Toast.clear()
      } catch (e) {
        //Toast.fail(e)
      }
    },
    /**
     * 打开Win
     * @param route 跳转路由
     * @param alias  路由标题
     */
    open(route, alias, menuName) {
      if (alias == 'task_execute') {
        if (menuName != '月任务') {
          this.actionSheetShow = true
        }
        this.queryParams.mnType = alias
        this.menuRoute = route
        if (menuName == '日任务') {
          this.queryParams.taskType = '0'
        } else if (menuName == '周任务') {
          this.queryParams.taskType = '1'
        } else if (menuName == '月任务') {
          this.queryParams.taskType = '2'
          if (this.menuRoute) {
            this.$ac.openWin({
              name: 'pointTaskList',
              url: './maintain-spotCheck-pointTaskList.html', // sub diretory file format: ./[subdir]-[subdir]-[filename].html
              pageParam: this.queryParams,
            })
          }
        } else if (menuName == '工艺点检') {
          this.queryParams.taskType = '3'
        }
        return
      } else if (alias == 'craft_execute') {
        this.$ac.openWin({
          name: alias,
          url: './maintain-spotCheck-crafts_check.html',
          type: 'fade',
          pageParam: {},
        })
        return
      }
      if (alias == null || alias == undefined) {
        alias = 'alias'
      }
      this.$ac.openWin({
        name: alias,
        url: './' + route + '.html',
        type: 'fade',
        pageParam: {},
      })
    },
    openwithDialog(route, alias) {
      this.actionSheetShow = true
      this.queryParams.mnType = alias
      this.menuRoute = route
    },
    onSelect(item) {
      this.queryParams.eqStatus = item.id
      if (this.menuRoute) {
        this.$ac.openWin({
          name: 'pointTaskList',
          url: './maintain-spotCheck-pointTaskList.html', // sub diretory file format: ./[subdir]-[subdir]-[filename].html
          pageParam: this.queryParams,
        })
      }
    },
    async initMenu() {
      Toast.loading({
        mask: true,
        forbidClick: true,
        duration: 0,
        message: 'Loading...',
      })
      try {
        let res = await _httpClient.get(_httpClient.getApiPrefix() + '/getAppRouters')
        if (res.code === 200) {
          //保存菜单和用户信息
          if (res.menus.length == 0) {
            storage.set('menu', [])
            this.list = []
          } else {
            storage.set('menu', res.menus[0].children)
            this.list = JSON.parse(storage.get('menu'))
          }


          storage.set('user', res.user)

          this.user = JSON.stringify(res.user)
          this.queryEquipmentInfo()

          this.querynum();
          //读取本地文件判断
          api.readFile({
            path: "widget://json/Employee.json"
          }, function (ret, err) {
            let list = JSON.parse(ret.data)["RECORDS"]
            // alert(list.length)

            for (let i = 0; i < list.length; i++) {
              let item = list[i]
              let user2 = JSON.parse(storage.get('user'))

              if (item.EmployeeID == user2.userName) {
                user2.employeeName = item.EmployeeName
                storage.set('user', user2)
                break
              }
            }
          });

        }
        Toast.clear()
      } catch (e) {
        alert(JSON.stringify(e))
      }
      return true
    },

    //删除别名
    deleteAlias() {
      var ajpush = api.require('ajpush')
      var param = { sequence: 102 }
      ajpush.deleteAlias(param, function (ret) { })
    },
  },
  destroyed() {
    this.$ac.removeEventListener({
      name: 'loginSuccess',
    })
  },
}
</script>

<style scoped>
.menu-col .van-col {
  display: inline-block;
  float: none;
  color: blue;
  text-align: center;
  vertical-align: middle;
  cursor: pointer;
}

.menu-col .van-icon {
  margin: 12px 0 6px;
  font-size: 3rem;
}

.text123 {
  font-size: 26px;
  color: #2100fa;
  font-weight: 800;
}

.buttonLeft {
  position: fixed;
  margin-top: 30px;
  margin-left: 75%;
  width: 90px;
  height: 40px;
  background-color: #ff8c00;
  border-color: #ff8c00;
}

.van-icon {
  position: relative;
  display: inline-block;
  font: normal normal normal 14px/1 'vant-icon';
  font-size: inherit;
  text-rendering: auto;
  -webkit-font-smoothing: antialiased;
}

.menu-col .van-col span {
  display: block;
  height: 20px;
  margin: -4px 0 4px;
  padding: 0 5px;
  color: #646566;
  font-size: 12px;
  line-height: 18px;
}

.textScroll {
  display: inline-block;
  position: fixed;
  top: 9.5rem;
  bottom: 0rem;
  overflow: scroll;
  right: 0;
  width: 100%;
  z-index: 1;
}
</style>